package com.na.tools;

import java.io.Closeable;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class CommonTools {

	public static void closeIO(Closeable io) {
		if (io != null) {
			try {
				io.close();
			} catch (IOException e) {}
		}
	}
	
	public static List<File> searchFiles(File dir, final FileFilter filter) {
		final List<File> result = new ArrayList<File>(512);
		dir.listFiles(new FileFilter() {
			@Override
			public boolean accept(File file) {
				if (file.isDirectory()) {
					List<File> files = searchFiles(file, filter);
					result.addAll(files);
					return false;
				}
				boolean accept = filter != null ? filter.accept(file) : true;
				if (accept) {
					result.add(file);
				}
				return accept;
			}
		});
		return result;
	}
	
	public static byte[] readFile(String file) {
		return readFile(new File(file));
	}
	
	public static byte[] readFile(File file) {
		try {
			return readFile(new FileInputStream(file));
		} catch (FileNotFoundException e) {
		}
		return null;
	}
	
	public static byte[] readFile(InputStream file) {
		try {
			byte[] buf = new byte[file.available()];
			file.read(buf);
			return buf;
		} catch (IOException e) {
		} finally {
			closeIO(file);
		}
		return null;
	}
	
	public static String[] split(String target, String... separators) {
		if (target == null || separators == null || separators.length == 0) {
			return new String[]{ target };
		}
		int from = 0, to = Integer.MAX_VALUE;
		List<String> strs = new ArrayList<String>();
		while (true) {
			String match = null;
			for (String s : separators) {
				int dot = target.indexOf(s, from);
				if (dot != -1 && dot < to) {
					to = dot;
					match = s;
				}
			}
			if (match == null) {
				return strs.toArray(new String[strs.size()]);
			}
			String str = target.substring(from, to);
			strs.add(str);
			from = to + match.length();
			to = Integer.MAX_VALUE;
		}
	}
	
	public static void printArray(Object[] arr, String separator) {
		if (arr == null || arr.length == 0) {
			System.out.println(arr);
			return;
		}
		StringBuilder buf = new StringBuilder();
		for (Object l : arr) {
			buf.append(l).append(separator);
		}
		buf.setLength(buf.length() - separator.length());
		System.out.println(buf);
	}
}
